package com.whpost.service.dao.t;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.whpost.service.entity.t.TRegion;
import com.whpost.service.entity.t.TRegion;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author YinZhuoyi
 * @since 2025-07-15
 */
public interface TRegionDao extends BaseMapper<TRegion> {

    @Select("select * from t_region where ${ew.sqlSegment}")
    @Results(id="tRegionMap",value = {
            @Result(column="pid",property="pRegion",
                    one=@One(
                            select="com.whpost.service.dao.t.TRegionDao.selectById")
            ),
            @Result(column="pid",property="pid")
    })
    List<TRegion> getTRegionList(@Param("ew") QueryWrapper wrapper);

    //自己和下级
    @Select("SELECT * FROM t_region START WITH id = #{id} CONNECT BY PRIOR id = pid")
    @ResultMap(value="tRegionMap")
    List<TRegion> getRegionXj(Long id);

    //查询下级，不包含自己
    @Select("SELECT * from t_region where id!=#{id} CONNECT BY PRIOR id = pid START WITH id = #{id}")
    @ResultMap(value="tRegionMap")
    List<TRegion> getRegionXjNoRoot(Long id);

    @Select("SELECT * from t_region where id=#{id}")
    @ResultMap(value="tRegionMap")
    TRegion getRegionById(String id);

    //树形查询
    @Select("SELECT LPAD(' ', (LEVEL - 1) * 4) || id AS indented_id, id, pid, jb, LEVEL AS tree_level, SYS_CONNECT_BY_PATH(name, ' > ') AS full_name, CONNECT_BY_ISLEAF AS is_leaf FROM t_region START WITH id = #{id} CONNECT BY NOCYCLE PRIOR id = pid ORDER SIBLINGS BY id")
    List<Map<String,String>> getRegionTree(Long id);

    //获取所有行政机构的id
    @Select("SELECT id FROM t_region START WITH id = #{id} CONNECT BY NOCYCLE PRIOR id = pid ORDER SIBLINGS BY id")
    List<Long> getAllId(Long id);

    @Update("UPDATE t_region SET jb = (SELECT parent.jb + 1 FROM t_region parent WHERE parent.id = #{id}) WHERE id IN (SELECT id FROM t_region START WITH id = #{id} CONNECT BY PRIOR id = pid MINUS SELECT #{id} FROM dual)")
    int updateJb(Long id);

    @Update("update t_region set pid=null,jb=1 where id=#{id}")
    int setPidNull(Long id);
}
